<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\CallOut;
use App\Admin\Actions\Sea;
use App\Admin\Actions\Del;
use App\Admin\Actions\ShenHe;
use App\Admin\Traits\tabMenu;
use App\Exports\ClientExport;
use App\Imports\Excels;
use App\Models\Client;
use App\Models\CrmConfig;
use App\Models\Department;
use App\Models\User;
use Carbon\Carbon;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;


class ClientController extends BaseController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '客户列表';


    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Client());
        $grid->exporter(new ClientExport());



        $grid->model()
            ->where('true_client', 1)
            ->where('in_sea', '<>', 1)
            ->with(['employee','houses','cars','baoxian','records','oneLastRecords'])
            ->orderBy('true_client_at','desc')
            ->orderBy('created_at', 'desc');


        $grid = $this->permissions($grid, true, true, true, true, false);

        $grid->column('id', __('ID'))->sortable();
        $grid->column('name', '姓名')->display(function ($model) {
            return "<a href='/admin/clients/$this->id/edit'>$model</a>";
        });

        self::callOut($grid);

        $grid->column('employee_id', '所属销售员')->using(User::Users());
        $grid->column('leader','上级主管')->display(function ($model){
            return Department::getLeader($this->employee_id);
        });
        $grid->column('employee.dep_l3','所属三级部门')->using(Department::getLevel(3));
        $grid->column('employee.dep_l2','所属二级部门')->using(Department::getLevel(2));
        $grid->column('employee.dep_l1','所属一级部门')->using(Department::getLevel(1));

        $grid->column('status', '客户类型')
            ->editable('select',CrmConfig::getKeyValue('client_status'));

        if(Admin::user()->isRole('employee')) {
            $grid->column('employee_status', '销售跟进状态')
                ->editable('select', CrmConfig::getKeyValue('follow_status'));
            $grid->column('quanzheng_status', '权证跟进状态')
                ->using(CrmConfig::getKeyValue('quanzheng_status'));
        }else if(Admin::user()->isRole('quanzheng')){
            $grid->column('employee_status', '销售跟进状态')
                ->using(CrmConfig::getKeyValue('follow_status'));
            $grid->column('quanzheng_status', '权证跟进状态')
                ->editable('select', CrmConfig::getKeyValue('quanzheng_status'));
        }else{
            $grid->column('employee_status', '销售跟进状态')
                ->using(CrmConfig::getKeyValue('follow_status'));
            $grid->column('quanzheng_status', '权证跟进状态')
                ->using(CrmConfig::getKeyValue('quanzheng_status'));
        }

        $grid->column('created_at', '创建时间');
        $grid->column('oneLastRecords.records','最新跟进记录')
            ->editable();

        self::newestRecords($grid);

        $grid->column('foo','未跟进天数')->display(function ($model){
            $nt = (int) ceil((time() - strtotime($this->last_updated_at)) / 60 / 60 / 24);
            return $nt > 3650 ? '从未' : $nt;
        });

//
//        $grid->tools(function ($tools){
//            $tools->append("<a class='btn btn-sm btn-primary' href='/admin/checkRepeat' target='_blank' >查重</a>");
//        });

        $grid->filter(function ($filter)  {
            self::filter($filter);
        });

        $grid->actions(function (Grid\Displayers\Actions $actions){
            $actions->disableView();
            $actions->disableEdit();
            $actions->disableDelete();
        });


        $grid->batchActions(function (Grid\Tools\BatchActions $batch) {
            $batch->add(new Sea());
            $batch->add(new ShenHe());
            $batch->add(new Del());
            $batch->disableDelete();
        });

        // 每页条数
        $grid->perPages([10, 20, 50, 100, 200, 500, 1000]);

        return $grid;
    }

    public function destroy($id)
    {
        $user = User::query()->where('id',$id)->whereIn('real_finished',[1,3])->exists();
        if($user){
            admin_toastr('审核中和审核通过的客户不可删除');
            return false;
        }
        parent::destroy($id);
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Client::findOrFail($id));

        $show->field('id', __('ID'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));

        return $show;
    }

    public function edit($id, Content $content)
    {
        $client_name = Client::getAllClients()[$id];
        $content
            ->title($this->title() . ' - ' . $client_name)
            ->description($this->description['edit'] ?? trans('admin.edit'))
            ->row(function ($row) use ($id) {
                $row->column(12, tabMenu::tabMenuList($id));
            })
            ->row(function ($row) use ($id) {
                $row->column(12, $this->form()->edit($id));
            });
        return $content;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Client);

        if(Admin::user()->isRole('employee')) {
            $form->select('employee_status', '销售跟进状态')->default(1)
                ->options(CrmConfig::getKeyValue('follow_status'));
            $form->select('quanzheng_status', '权证跟进状态')->default(1)
                ->options(CrmConfig::getKeyValue('quanzheng_status'))->readOnly();
        }else if(Admin::user()->isRole('quanzheng')) {
            $form->select('employee_status', '销售跟进状态')->default(1)
                ->options(CrmConfig::getKeyValue('follow_status'))->readOnly();
            $form->select('quanzheng_status', '权证跟进状态')->default(1)
                ->options(CrmConfig::getKeyValue('quanzheng_status'));
        }else{
            $form->select('employee_status', '销售跟进状态')->default(1)
                ->options(CrmConfig::getKeyValue('follow_status'))->readOnly();
            $form->select('quanzheng_status', '权证跟进状态')->default(1)
                ->options(CrmConfig::getKeyValue('quanzheng_status'))->readOnly();
        }

        $form->fieldset('个人信息', function ($form) {
            $form->text('name', '姓名')->required();

            $form->mobile('mobile', '手机号码')->required();
            $form->select('sex', '性别')->options([1 => '男', 2 => '女']);
            $form->number('age', '年龄');
            $form->select('marriage', '婚姻状况')->options(Client::marriage);
            $form->select('education', '学历')->options(Client::education);
            $form->text('china_id', '身份证号');
            $form->datetime('china_id_valid', '身份证有效期');
            $form->distpicker([
                'current_prov' => '省份',
                'current_city' => '市',
                'current_area' => '区'
            ], '现居住地');
            $form->text('current_street', '当前居住-街道');
            $form->distpicker([
                'born_prov' => '省份',
                'born_city' => '市',
                'born_area' => '区'
            ], '籍贯地址');
            $form->text('born_street', '籍贯-街道');
        });
        $form->fieldset('资产信息', function ($form) {
            $form->currency('income', '打卡工资')->symbol('￥');
            $form->currency('family_in', '其他收入')->symbol('￥');
            $form->currency('family_out', '家庭月支出')->symbol('￥');
        });
        $form->fieldset('社保信息', function ($form) {
            $form->switch('shebao', '有无社保')->states(CrmConfig::SWITCH_STATES_YM);
            $form->currency('shebao_in', '个人月缴存额')->symbol('￥');
        });
        $form->fieldset('公积金信息', function ($form) {
            $form->switch('gongjijin', '有无公积金')->states(CrmConfig::SWITCH_STATES_YM);
            $form->currency('gongjijin_in', '个人月缴存额')->symbol('￥');
        });
        $form->fieldset('工作信息', function ($form) {
            $form->text('company', '单位名称');
            $form->text('company_address', '单位地址');
            $form->text('company_type', '行业类型');
            $form->select('company_belong', '单位性质')->options(Client::company_type);
            $form->select('company_post', '公司职位')->options(Client::company_post);
        });
        $form->fieldset('房产信息', function ($form) {
            $form->hasMany('houses', '房产信息', function (Form\NestedForm $form) {
                $form->select('usefor', '房屋状态')->options(CrmConfig::getKeyValue('house_use_for'));
                $form->select('own_type','房产所有权')->options(CrmConfig::getKeyValue('own_type'));
                $form->select('pay_type', '付款方式')->options(CrmConfig::getKeyValue('money_pay_type'));
                $form->select('status', '是否抵押')->options([1 => '是', 2 => '否']);
                $form->text('value', '房产价值（万）');
                $form->text('house_size', '房产面积(㎡)');
                $form->text('house_addr', '房产地址');
            });
        });
        $form->fieldset('车产信息', function ($form) {
            $form->hasMany('cars', '车产信息', function (Form\NestedForm $form) {
                $form->select('pay_type', '付款方式')->options(CrmConfig::getKeyValue('money_pay_type'));
                $form->select('status', '是否抵押')->options([1 => '是', 2 => '否']);
                $form->text('value', '车产价值（万）');
                $form->date('buy_time', '购入时间');
            });
        });
        $form->fieldset('保险信息', function ($form) {
            $form->hasMany('baoxian', '保险信息', function (Form\NestedForm $form) {
                $form->text('bx_company', '保险公司');
                $form->text('bx_type', '保险类型');
                $form->text('bx_tbr', '投保人');
                $form->text('value', '年缴费用');
                $form->date('buy_time', '购买日期');
                $form->switch('bx_stop', '是否断缴');
            });
        });
        $form->fieldset('负债信息', function ($form) {
            $form->currency('debt', '未结清放贷余额')->symbol('￥');
            $form->currency('monthly_debt', '每月还贷额')->symbol('￥');
        });
        $form->fieldset('资质情况备注', function ($form) {
            $form->switch('had_dk','有无贷款');
            $form->textarea('dk_history', '贷款历史');
            $form->textarea('zx_history', '征信情况');
            $form->textarea('note', '资质情况备注');
        });
        $form->divider();

        $users = User::Users();


        $form->select('employee_id', '所属销售员')
            ->options($users)->value(Admin::user()->id)->readonly();
        $form->select('quanzheng_id', '所属权证人')
            ->options($users)->value(Admin::user()->id)->readonly();
        $form->tools(function (Form\Tools $tools) {
            $tools->disableDelete();
        });

        // 真实客户
        $form->hidden('true_client')->default(1);

        // 自动变为意向客户
        $form->saving(function (Form $form){
            if(in_array($form->status, [1,2])){
                $form->true_client_at = Carbon::now()->toDateTimeString();
                $form->true_client = 1;
            }else{
                $form->true_client_at = NULL;
                $form->true_client = 0;
            }
        });

        return $form;
    }

}
